import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button, Steps, Divider, Progress, Card } from 'antd';
import { 
  ArrowLeftOutlined, 
  EnvironmentOutlined,
  PhoneOutlined,
  TruckOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import { getOrders, updateOrderStatus, updateProductStock } from '../../utils/storage';
import { orderAPI } from '../../services/api';
import { message } from '../../utils/message';
import { giveOrderPoints } from '../../utils/points';
import './OrderDetail.css';

const { Step } = Steps;

const OrderDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [order, setOrder] = useState(null);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);
  const [afterSale, setAfterSale] = useState(null);

  useEffect(() => {
    loadOrderDetail();
    // 新增：加载售后信息
    const afterSales = JSON.parse(localStorage.getItem('afterSales') || '[]');
    const found = afterSales.find(item => item.orderId === id);
    if (found) setAfterSale(found);
  }, [id]);

  useEffect(() => {
    // 监听页面可见性变化，当页面重新可见时刷新订单数据
    const handleVisibilityChange = () => {
      if (!document.hidden) {
        loadOrderDetail();
      }
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);
    
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, []);

  const loadOrderDetail = () => {
    const orders = getOrders();
    const orderDetail = orders.find(o => o.id === parseInt(id));
    setOrder(orderDetail);
    setLoading(false);
  };

  const getStatusText = (status) => {
    const statusMap = {
      pending: '待付款',
      paid: '待发货',
      shipped: '运输中',
      delivered: '已收货',
      cancelled: '已取消',
      refund: '退款中'
    };
    return statusMap[status] || status;
  };

  const getOrderSteps = (order) => {
    const steps = [
      { 
        title: '提交订单', 
        description: new Date(order.createTime).toLocaleString(),
        status: 'finish'
      },
      { 
        title: '付款成功', 
        description: order.payTime ? new Date(order.payTime).toLocaleString() : '',
        status: order.status === 'pending' ? 'wait' : 'finish'
      },
      { 
        title: '商家发货', 
        description: order.shipTime ? new Date(order.shipTime).toLocaleString() : '',
        status: ['shipped', 'delivered'].includes(order.status) ? 'finish' : 
                order.status === 'paid' ? 'process' : 'wait'
      },
      { 
        title: '确认收货', 
        description: order.deliverTime ? new Date(order.deliverTime).toLocaleString() : '',
        status: order.status === 'delivered' ? 'finish' : 
                order.status === 'shipped' ? 'process' : 'wait'
      }
    ];

    return steps;
  };

  const getLogisticsInfo = (order) => {
    const baseTime = order.shipTime || Date.now();
    const now = Date.now();
    
    if (order.status === 'paid') {
      return {
        status: '待发货',
        description: '商家正在准备您的商品，预计24小时内发货',
        estimatedDays: 1,
        progress: 10
      };
    } else if (order.status === 'shipped') {
      const hoursShipped = Math.floor((now - baseTime) / (1000 * 60 * 60));
      const daysShipped = Math.floor(hoursShipped / 24);
      
      return {
        status: '运输中',
        description: `您的包裹已发货${'24小时'}，即将送达`,
        estimatedDays: 2 - daysShipped,
        progress: 100
      };
    } else if (order.status === 'delivered') {
      return {
        status: '已送达',
        description: '您的包裹已成功送达，感谢您的购买',
        estimatedDays: 0,
        progress: 100
      };
    }
    
    return null;
  };

  const handlePayOrder = async () => {
    setActionLoading(true);
    
    try {
      // 跳转到支付页面
      navigate('/app/payment', {
        state: {
          orderId: order.id,
          orderData: {
            ...order,
            fromCart: false
          }
        }
      });
    } catch (error) {
      message.error('操作失败');
    } finally {
      setActionLoading(false);
    }
  };

  const handleViewLogistics = () => {
    message.info('查看物流详情功能开发中');
  };

  const handleConfirmReceive = async () => {
    setActionLoading(true);
    
    try {
      // 调用API更新订单状态为delivered
      const response = await orderAPI.updateOrderStatus(order.id, 'delivered');
      if (response.success) {
        // 订单确认收货时给予积分奖励
        giveOrderPoints(order.totalAmount);
        
        // 更新商品库存和销量（确保本地状态更新）
        if (order.products && order.products.length > 0) {
          order.products.forEach(product => {
            updateProductStock(product.id, product.quantity);
          });
        }
        
        message.success('确认收货成功，获得积分奖励');
        // 重新加载订单详情
        loadOrderDetail();
      } else {
        message.error(response.message || '操作失败');
      }
    } catch (error) {
      console.error('确认收货失败:', error);
      message.error('操作失败，请重试');
    } finally {
      setActionLoading(false);
    }
  };

  const handleReview = () => {
    message.info('评价功能开发中');
  };

  const handleCancelOrder = async () => {
    setActionLoading(true);
    
    try {
      // 调用API更新订单状态为cancelled
      const response = await orderAPI.updateOrderStatus(order.id, 'cancelled');
      if (response.success) {
        message.success('订单已取消');
        // 重新加载订单详情
        loadOrderDetail();
      } else {
        message.error(response.message || '操作失败');
      }
    } catch (error) {
      console.error('取消订单失败:', error);
      message.error('操作失败，请重试');
    } finally {
      setActionLoading(false);
    }
  };

  const handleBuyAgain = () => {
    // 跳转到首页
    navigate('/app');
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '40px' }}>
        加载中...
      </div>
    );
  }

  if (!order) {
    return (
      <div style={{ textAlign: 'center', padding: '40px' }}>
        订单不存在
      </div>
    );
  }

  const steps = getOrderSteps(order);
  const logisticsInfo = getLogisticsInfo(order);

  return (
    <div className="order-detail">
      {/* 头部导航 */}
      <div className="order-detail-header">
        <Button 
          type="text" 
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
        />
        <span className="header-title">订单详情</span>
      </div>

      {/* 订单状态 */}
      <div className="order-status-section">
        <div className="status-header">
          <div className="status-text">{getStatusText(order.status)}</div>
          <div className="order-no">订单号：{order.orderNo}</div>
        </div>
        
        {order.status !== 'cancelled' && order.status !== 'refund' && (
          <>
            <Steps direction="vertical" size="small" className="order-steps">
              {steps.map((step, index) => (
                <Step 
                  key={index}
                  title={step.title} 
                  description={step.description}
                  status={step.status}
                />
              ))}
            </Steps>

            {/* 物流信息卡片 */}
            {logisticsInfo && (
              <Card className="logistics-card" size="small">
                <div className="logistics-header">
                  <TruckOutlined style={{ color: '#1890ff', marginRight: '8px' }} />
                  <span className="logistics-title">物流信息</span>
                </div>
                <div className="logistics-content">
                  <div className="logistics-status">{logisticsInfo.status}</div>
                  <div className="logistics-description">{logisticsInfo.description}</div>
                  {logisticsInfo.estimatedDays > 0 && (
                    <div className="logistics-estimate">
                      <ClockCircleOutlined style={{ marginRight: '4px' }} />
                      预计即将送达
                    </div>
                  )}
                  <Progress 
                    percent={logisticsInfo.progress} 
                    size="small"
                    strokeColor="#1890ff"
                    className="logistics-progress"
                  />
                </div>
              </Card>
            )}
          </>
        )}
      </div>

      {/* <Divider /> */}

      {/* 收货地址 */}
      <div className="address-section">
        <div className="section-title">
          <EnvironmentOutlined /> 收货地址
        </div>
        <div className="address-info">
          <div className="receiver-info">
            <span className="receiver-name">{order.address.name}</span>
            <span className="receiver-phone">
              <PhoneOutlined /> {order.address.phone}
            </span>
          </div>
          <div className="address-detail">
            {order.address.province} {order.address.city} {order.address.district} {order.address.detail}
          </div>
        </div>
      </div>

      {/* <Divider /> */}

      {/* 商品信息 */}
      <div className="order-products-section">
        <div className="section-title">商品信息</div>
        {order.products.map((product, index) => (
          <div key={index} className="order-product-item">
            <img 
              src={product.images[0]} 
              alt={product.name}
              className="product-image"
            />
            <div className="product-info">
              <div className="product-name">{product.name}</div>
              {product.selectedSpecs && (
                <div className="product-specs">
                  {Object.entries(product.selectedSpecs).map(([key, value]) => (
                    <span key={key}>{key}: {value} </span>
                  ))}
                </div>
              )}
              <div className="product-price-qty">
                <span className="price">¥{product.price}</span>
                <span className="quantity">x{product.quantity}</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* <Divider /> */}

      {/* 订单金额 */}
      <div className="order-amount-section">
        <div className="section-title">订单金额</div>
        <div className="amount-item">
          <span>商品总额</span>
          <span>¥{order.originalAmount.toFixed(2)}</span>
        </div>
        <div className="amount-item">
          <span>运费</span>
          <span>免运费</span>
        </div>
        {order.pointsDiscount > 0 && (
          <div className="amount-item discount">
            <span>积分抵扣</span>
            <span>-¥{order.pointsDiscount.toFixed(2)}</span>
          </div>
        )}
        <div className="amount-total">
          <span>实付款</span>
          <span className="total-amount">¥{order.totalAmount.toFixed(2)}</span>
        </div>
      </div>

      {/* <Divider /> */}

      {/* 订单信息 */}
      <div className="order-info-section">
        <div className="section-title">订单信息</div>
        <div className="info-item">
          <span>订单编号</span>
          <span>{order.orderNo}</span>
        </div>
        <div className="info-item">
          <span>下单时间</span>
          <span>{new Date(order.createTime).toLocaleString()}</span>
        </div>
        {order.payTime && (
          <div className="info-item">
            <span>支付时间</span>
            <span>{new Date(order.payTime).toLocaleString()}</span>
          </div>
        )}
        {order.shipTime && (
          <div className="info-item">
            <span>发货时间</span>
            <span>{new Date(order.shipTime).toLocaleString()}</span>
          </div>
        )}
        {order.deliverTime && (
          <div className="info-item">
            <span>收货时间</span>
            <span>{new Date(order.deliverTime).toLocaleString()}</span>
          </div>
        )}
        <div className="info-item">
          <span>支付方式</span>
          <span>
            {order.paymentMethod === 'alipay' ? '支付宝' : 
             order.paymentMethod === 'wechat' ? '微信支付' : 
             order.paymentMethod === 'bankcard' ? '银行卡支付' : '支付宝'}
          </span>
        </div>
      </div>

      {/* 底部操作按钮 - 整合了Orders组件的功能 */}
      <div className="order-actions">
        {/* 待付款状态 */}
        {order.status === 'pending' && (
          <div className="action-buttons-group">
            <Button 
              size="large"
              style={{ marginRight: '12px' }}
              loading={actionLoading}
              onClick={handleCancelOrder}
            >
              取消订单
            </Button>
            <Button 
              type="primary" 
              size="large"
              loading={actionLoading}
              onClick={handlePayOrder}
            >
              立即付款
            </Button>
          </div>
        )}
        
        {/* 待发货状态 */}
        {order.status === 'paid' && (
          <div className='action-buttons-group' style={{display: 'flex', justifyContent: 'left', alignItems: 'center', width: '100%', height: '20px', paddingLeft: '5px'}}>
            <Button 
              type="primary" 
              loading={actionLoading}
              onClick={handleCancelOrder}
            >
              取消订单
            </Button>
          </div>
        )}
        
        {/* 运输中状态 */}
        {order.status === 'shipped' && (
            <Button 
              type="primary" 
              size="large"
              block
              loading={actionLoading}
              onClick={handleConfirmReceive}
            >
              确认收货
            </Button>
        )}
        
        {/* 已确认收货/可评价状态 */}
        {order.status === 'delivered' && (
          <Button 
            type="primary" 
            size="large"
            block
            onClick={() => message.info('评价功能开发中')}
          >
            评价商品
          </Button>
        )}

        {/* 已取消状态 */}
        {order.status === 'cancelled' && (
          <Button 
            type="primary" 
            size="large"
            block
            onClick={handleBuyAgain}
          >
            再来一单
          </Button>
        )}

        {/* 退款中状态 */}
        {order.status === 'refund' && (
          <div className="refund-status">
            <span style={{ color: '#ff4d4f' }}>退款处理中，请耐心等待</span>
          </div>
        )}

        {/* 已收货状态 */}
        {order.status === 'delivered' && !afterSale && (
          <Button type="primary"
                  size='large'
                  block
                  onClick={() => navigate(`/app/after-sale/apply/${id}`)}>
            申请售后
          </Button>
        )}

        {/* 已申请售后状态 */}
        {afterSale && (
          <Button
              type="primary"
              size="large"
              block
              onClick={() => navigate(`/app/after-sale/${afterSale.id}`)}>
            查看售后进度
          </Button>
        )}
      </div>
    </div>
  );
};

export default OrderDetail;